﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using Model;
using Service;
using Resources;

public partial class Systems : System.Web.UI.Page
{
    readonly ReferenceDataService _ReferenceDataService = new ReferenceDataService();
    readonly StockService _StockService = new StockService();
    EquipmentSystem _system = new EquipmentSystem();
    private DirectService _DirectService = new DirectService();
    

    protected void Page_Load(object sender, EventArgs e)
    {

      //  lblTotalSystem.Text = "Total system:" + _ReferenceDataService.GetSystems().Count;

        //txtHiddenSystemId.Text = Request.QueryString["systemsId"];
        if (Session["whereClause"] == null)
            Session["whereClause"] = txtHiddenWhereClause.Text;
        if (Session["orderByClause"] == null)
            Session["orderByClause"] = txthiddenOrderbyClause.Text;
        grdSystem.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text) ? Int32.Parse(txtHiddenPageIndex.Text) : 0;

        new Utility().SetRowToDisplay(grdSystem, Session["rowsToSDisplay"]);
        if (!IsPostBack)
        {
            
            if (Session["pageIndex"] != null)
            {
                grdSystem.PageIndex = Int32.Parse(Session["pageIndex"].ToString());

            }



            /* 
             * 1. number of equipments
             * 2. select the element 
             * */
            

        }
        else
        {
            //  SystemList = new DirectService().DataTableToIlistSystem(GetWhereClause(), GetOrderClause());
            txtHiddenPageIndex.Text = "0";
            lblTotalSystem.Text = "Total systems : " + new DirectService().GetSystemDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            int number = +new DirectService().GetSystemDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            if (number == 0)
            {
                grdSystem1.Visible = true;
            }
            else
            {
                grdSystem.Visible = true;
                grdSystem1.Visible = false;
            }
        }
        grdSystem.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text) ? Int32.Parse(txtHiddenPageIndex.Text) : 0;
    }
    private int GetSystemId()
    {
        return !String.IsNullOrEmpty(Request.QueryString["systemId"]) ? Int32.Parse(Request.QueryString["systemId"]) : 0;
        
    }
    protected string GetWhereClauseDemo()
    {
        return " where System.System=" + "'" + txtSystem.Text + "'"; 
    }
    protected string GetWhereClause()
    {
        string whereClause = string.Empty;
        string and = "";
        string str = "";

        // Prepare by equipement
        int i = 0;
        if (!string.IsNullOrEmpty(txtSystemId.Text))
        {
            if (int.TryParse(txtSystemId.Text, out i))
            {
                and = " and ";
                str = " where System.SystemId=" + Int32.Parse(txtSystemId.Text);
                if (txtSystemLabel.Text != string.Empty)
                {
                    str += " " + "and" + " " + "System.System=" + "'" + txtSystemLabel.Text + "'";
                    and = " and ";
                }
            } else
            {
                grdSystem.Visible = false;
                grdSystem1.Visible = true;
                lblTotalSystem.Text = "Total system: 0"; 
                return null;
            }
        }
        else
        {
            if (txtSystemLabel.Text != string.Empty)
            {
                str += " " + "where" + " " + "System.System like" + "'%" + txtSystemLabel.Text + "%'";
                and = " and ";
            }
        }
       
        if (!String.IsNullOrEmpty(str))
            whereClause =  str + " ";
        return whereClause;
    }
    protected string GetOrderClause()
    {
        return " Order by System.System";
    }
    
    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }

    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?
                       Int32.Parse(Session["pageIndex"].ToString())
                   : 0;
    }
   
    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdSystem.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdSystem.PageIndex.ToString();
        Session["pageIndex"] = grdSystem.PageIndex;

    }
    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdSystem.EditIndex = -1;
    }
    protected void grdEquipment_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //block to add message
            
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                LinkButton deleteButton = (LinkButton)e.Row.Cells[1].Controls[0];
                deleteButton.Attributes.Add("onclick", "return confirm('" + Resource.ConfirmDeleteMessage  + "?');");    
            }
        }
    }
    protected void bntFilter_Click(object sender, EventArgs e)
    {
        Session["whereClause"] = GetWhereClause();
        Session["orderByClause"] = GetOrderClause();
        txthiddenOrderbyClause.Text = GetOrderClause();
        txtHiddenWhereClause.Text = GetWhereClause();
        Session["defaultTabIndex"] = 0;

        ClearControlSearch();
            
    }
    private void ClearControlSearch()
    {
        txtSystemId.Text = "";
        txtSystemLabel.Text = ""; 
    }
    private void ClearControlAdd()
    {
        txtSystem.Text = "";
    }
    protected void btnAdd_Click2(object sender, EventArgs e)
    {
        _system.SystemLabel = txtSystem.Text;
        _ReferenceDataService.SaveSystem(_system);
        
    }
    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grdSystem_Sorted(object sender, EventArgs e)
    {
        grdSystem.DataBind();

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {


        AddSystem();
        
       
    }
    private void AddSystem()
    {

        IList list = new ArrayList();
        list = _StockService.GetSystem();

        for (int i = 0; i < list.Count; i++)
        {
            if (((EquipmentSystem)list[i]).SystemLabel == txtSystem.Text)
            {
                lblMessage.Visible = true;
                lblMessageValidate.Text = ""; 
                return;
            }


        }
        if (txtSystem.Text != string.Empty)
        {
            lblMessage.Visible = false;
            _system.SystemId = 0;
            _system.SystemLabel = txtSystem.Text;
            _ReferenceDataService.SaveSystem(_system);
            //  new DirectService().GetSystemDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            lblTotalSystem.Text = "Total system:" + _ReferenceDataService.GetSystems().Count;
            Session["defaultTabIndex"] = 0;

            grdSystem1.Visible = false;
            ClearControlAdd();
            lblMessageValidate.Text = Resource.MessageValidate;
        }
        
    }
    protected void grdSystem1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grdSystem_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (e.Cancel == false)
        {
            bool flag = true;
            if (flag == false)
            {
                GridViewRow row = grdSystem.Rows[e.RowIndex];
                _system.SystemId = Int32.Parse(row.Cells[2].Text);
                _system.SystemLabel = row.Cells[3].Text;
            }
        }
    }
    protected void grdSystem_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Delete"))
        {
            int authorId = Convert.ToInt32(grdSystem.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
            _StockService.DeleteSystem(authorId);
            Response.Redirect("Systems.aspx");
        }
        new Utility().SetSelectedColorToGridView(e, grdSystem);
    }
    protected void grdSystem_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

        Response.Redirect("Systems.aspx");

    }
    protected void grdSystem_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdSystem.EditIndex = e.NewEditIndex;
    }
    protected void grdSystem_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = grdSystem.Rows[e.RowIndex];
        _system.SystemId = Int32.Parse(row.Cells[2].Text);

        //get updated cell from authorGridView
        _system.SystemLabel = e.NewValues[0].ToString();
        
    }
    protected void dsSystem_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.ReturnValue != null) lblTotalSystem.Text = "Total system:" + ((DataTable)e.ReturnValue).Rows.Count;
    }
}
